package cn.lysj.framework.store.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.lysj.framework.base.BaseController;
import cn.lysj.framework.base.BaseService;
import cn.lysj.framework.common.OrderPayConstant;
import cn.lysj.framework.common.annotation.CurrentUser;
import cn.lysj.framework.common.annotation.SystemLog;
import cn.lysj.framework.common.domain.Role;
import cn.lysj.framework.common.domain.User;
import cn.lysj.framework.common.domain.UserRole;
import cn.lysj.framework.common.dto.MerchantInfoDto;
import cn.lysj.framework.common.service.RoleService;
import cn.lysj.framework.common.service.UserRoleService;
import cn.lysj.framework.common.service.UserService;
import cn.lysj.framework.common.utils.pagination.PageUtil;
import cn.lysj.framework.common.utils.pagination.PageVo;
import cn.lysj.framework.common.utils.web.ParamUtil;
import cn.lysj.framework.common.utils.web.Resp;
import cn.lysj.framework.common.validate.Message;
import cn.lysj.framework.common.validate.annotation.Pattern;
import cn.lysj.framework.common.validate.annotation.Validator;
import cn.lysj.framework.common.validate.entity.Medusa;
import cn.lysj.framework.order.dto.AjaxResp;
import cn.lysj.framework.store.domain.Store;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.List;

/**
 * @ Author ：drj.
 * @ Date  ：Created in 16:09 2018/11/15
 * @ Description:门店员工管理
 **/
@RestController
@RequestMapping("/store/user")
public class UserManageController extends BaseController<User> {

    @Resource
    private UserService userService;
    @Resource
    private RoleService roleService;
    @Resource
    private UserRoleService userRoleService;

    @Override
    public BaseService<User> getService() {
        return userService;
    }


    @SystemLog(description = "查询门店对应的员工信息")
    @Override
    @GetMapping("/list")
    @ApiOperation(value = "用户列表+查询")
    public Resp list(@CurrentUser User user, PageVo pageVo) {
        Pageable pageable = PageUtil.initPage(pageVo);
        Page<User> page = userService.getRepository().findByStoreId(pageable, user.getStoreId());
        for (User user1 : page.getContent()) {
            user.setRoles(userRoleService.findUserRoleByUserId(user1.getId()));
        }
        return new Resp(page);
    }


    @PostMapping("/save_user")
    @ApiOperation(value = "添加用户")
    public Resp save(@CurrentUser User user, @Validator User entity, String[] roleIds) {
        if (ParamUtil.isBlank(entity.getUsername())) {
            return new Resp(Resp.PARAM_ERROR, "用户名不能为空");
        }
        User userQuery = userService.findByUsername(entity.getUsername());
        if (userQuery != null) {
            return new Resp(Resp.PARAM_ERROR, "用户名已存在");
        }
        entity.setPassword(new BCryptPasswordEncoder().encode(entity.getPassword()));
        entity.setStoreId(user.getStoreId());//将员工门店id设置为当前商户的id
        userService.save(entity);
        if (!ParamUtil.isBlank(roleIds)) {
            for (String s : roleIds) {
                if (!roleService.countRoleId(s)) {
                    return new Resp(Resp.PARAM_ERROR, "角色信息有误");
                }
                Role role = roleService.findOne(s);
                if ("管理员".equals(role.getName()) || "商户".equals(role.getName())) {
                    return new Resp(Resp.PARAM_ERROR, "不允许添加管理员或者商户");
                }
                UserRole ur = new UserRole();
                ur.setRoleId(s);
                ur.setUserId(entity.getId());
                userRoleService.save(ur);
            }
        } else {
            List<Role> roles = roleService.findByDefaultRole(true);
            if (!ParamUtil.isBlank(roles)) {
                for (Role role : roles) {
                    UserRole ur = new UserRole();
                    ur.setRoleId(role.getId());
                    ur.setUserId(entity.getId());
                    userRoleService.save(ur);
                }
            }
        }

        return new Resp("添加成功");
    }


    @PostMapping("/update_user")
    @ApiOperation(value = "修改用户")
    public Resp update(User entity, String[] roleIds) {
        if (ParamUtil.isBlank(entity.getId())) {
            return new Resp(Resp.PARAM_ERROR, "参数错误，请重试");
        }
        User user = userService.findOne(entity.getId());
        if (user == null) {
            return new Resp(Resp.PARAM_ERROR, "查无此用户");
        }
        //获取Hutool拷贝实例
        CopyOptions copyOptions = CopyOptions.create();
        //忽略为null值得属性
        copyOptions.setIgnoreNullValue(true);
        //进行属性拷贝
        BeanUtil.copyProperties(entity, user, copyOptions);
        //对实体类中的@validation注解进行校验
        Medusa medusa = Message.getMsg(user, Message.getMap("password", Pattern.class));
        if (!medusa.isFlag()) {
            return new Resp(Resp.PARAM_ERROR, medusa.getMessage());
        }

        userRoleService.deleteByUserId(user.getId());
        for (String s : roleIds) {
            if (!roleService.countRoleId(s)) {
                return new Resp(Resp.PARAM_ERROR, "角色信息有误");
            }
            Role role = roleService.findOne(s);
            if ("管理员".equals(role.getName()) || "商户".equals(role.getName())) {
                return new Resp(Resp.PARAM_ERROR, "不允许修改管理员或者商户");
            }
            UserRole ur = new UserRole();
            ur.setRoleId(s);
            ur.setUserId(entity.getId());
            userRoleService.save(ur);
        }
        return new Resp("修改成功");

    }

}
